define( [
		'module',
		'jquery',
		'backbone',
		'marionette',
		'text!templates/newBookView.html',
	  	'jqueryui',	
		],
function( module, $, Backbone, Marionette, ItemHTML ) {
	console.log("Loading module " + module.id + " from " + module.uri + "...");

	var AddBook = Backbone.Marionette.ItemView.extend({
//		template: "#row-template",
//		tagName: "tr"
//		template: "#item-view",
		template: undefined,
		tagName:"div",
		className:"bookContainer",

		initialize: function() {
			console.log("addBookView: initialize - entry");
			this.template = _.template(ItemHTML);
		},
		/* get the template from external file, do not polute
		 * the main page with template snippets
		 */

		 onShow: function() {
			console.log("addBookView: onShow fires ...");
			$("#releaseDate").datepicker();
		 },

		 saveFormData: function(str) {
			 console.log("addBookView: saveFormData called ... " + str );
		 },

		addBook:function(e) {
			e.preventDefault();
			var formData = {};
			var f;
			debugger;
			$("#addBook div").children("input").each(function(i, el){
				debugger;
				if( el.files && el.files[0] ) {
					f = el.files[0];
					console.log("Processing image");
    				// Only process image files. Image files
					// does not releal the path information, just
					// to content accessible via the FileReader.
    				if (f.type.match('image.*')) {
				   	var reader = new FileReader();
						// Need a closure to capture the file information.
						reader.onload = (function(ctx, theFile) {
      					return function(e) {
								console.log(e.target.result);
								formData.coverImage=e.target.result;
								// trigger even on the context object
								// once the content of the file is loaded
								// into the form structure
								debugger;
								appCTX.trigger('form:processed', JSON.stringify(formData));
      					};
    					})(this, f);

 		  			 	// Trigger the Read operation for the selected image. The callback
						// will get the URL stream, which is base64 coded stream.
    					reader.readAsDataURL(f);
					} else {
						console.error("You have to pick an image file");
					}
				} else {
					if( el.id === "releaseDate" ) {
						// Without jQuery UI, providing just a year in the input field ...
						// formData[el.id] = new Date($(el).val(), 1, 1).getTime()
						formData[el.id] = $("#releaseDate").datepicker("getDate").getTime();
						// if jQueryUI is used ...
					} else {
						formData[el.id] = $(el).val();
					}
				}
			});
		},

		events: {
			"click #add_new_book":"addBook" 
		}
	});

	return AddBook;
});
